//
//  TencentCosContext.swift
//  Center
//
//  Created by 蒋晨成 on 2022/2/16.
//

import Center_OSS
import Center_RPC
import Foundation

class TencentCOSContext: TencentCOSCenterContextual {
    func covert(pathType: Azir_Gateway_ResourcePathType) -> DataType? {
        switch pathType {
        case .pic:
            return .pic
        case .video:
            return .video
        case .audio:
            return .audio
        default:
            return nil
        }
    }

    func getUploadToken(type: Int64, complete: @escaping (Result<COSUploadConfiguration, Error>) -> Void) {
        RPCCenter.azir.getUploadToken(bizType: type) { [weak self] result in
            switch result {
            case .success(let response):
                var paths = [DataType: String]()
                for resourcePath in response.paths {
                    guard let dataType = self?.covert(pathType: resourcePath.rpType) else { continue }
                    paths[dataType] = resourcePath.path
                }
                let configuration = COSUploadConfiguration(
                    secretID: response.tmpSecretID,
                    secretKey: response.tmpSecretKey,
                    token: response.token,
                    startDate: Date(timeIntervalSince1970: TimeInterval(response.tokenStartAt)),
                    expirationDate: Date(timeIntervalSince1970: TimeInterval(response.tokenExpireAt)),
                    regionName: response.region,
                    bucket: response.bucket,
                    prefix: response.prefix,
                    paths: paths
                )
                complete(.success(configuration))

            case .failure(let error):
                complete(.failure(error))
            }
        }
    }
}
